<template>
  <div>
    <div class="r-header">
      <div class="header-item">
        <el-radio-group v-model="tabData">
          <el-radio-button label="river">最新</el-radio-button>
          <el-radio-button label="region">时间段</el-radio-button>
        </el-radio-group>
      </div>
      <div v-if="tabData === 'river'" class="header-item">
        <span>时间：</span>
        <!-- <el-date-picker size="small" v-model="daysdate" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker> -->
        <el-date-picker
          size="small"
          v-model="daysdate"
          type="month"
          placeholder="选择日期"
        >
        </el-date-picker>
      </div>
      <div v-if="tabData === 'region'" class="header-item">
        <span>时间：</span>
        <el-date-picker
          v-model="dataRange"
          type="monthrange"
          value-format="yyyy-MM"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div>
      <div class="header-item">
        <span>监测项目：</span>
        <el-select
          size="small"
          v-model="bussinessData"
          multiple
          collapse-tags
          style="margin-left: 20px"
          placeholder="请选择"
          @change="selectChange"
        >
          <el-option
            v-for="item in bussinessItemList"
            :key="item.itemCode"
            :label="item.itemName"
            :value="item.itemCode"
          >
          </el-option>
        </el-select>
      </div>
      <div class="header-item">
        <span>是否超标：</span>
        <el-switch
          v-model="isOver"
          active-color="#13ce66"
          inactive-color="#cccccc"
        >
        </el-switch>
      </div>
    </div>
    <div class="header-btns">
      <el-button
        class="query-btn"
        type="primary"
        icon="el-icon-search"
        size="mini"
        @click="handleQuery"
        >查询</el-button
      >
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
      >
      <!-- <el-button type="warning" icon="el-icon-download" size="mini" plain
                v-hasPermi="['system:user:export']">导出</el-button> -->
    </div>
    <div class="content">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column label="序号">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="点位名称">
          <template slot-scope="scope">{{ scope.row.SegmentName }}</template>
        </el-table-column>
        <el-table-column prop="RiverName" label="所属河流/湖库" width="120">
        </el-table-column>
        <el-table-column
          prop="SampleDate"
          label="监测时间"
          show-overflow-tooltip
          min-width="180"
        >
        </el-table-column>
        <!-- <el-table-column prop="segmentIndex" label="水质指数" >
                </el-table-column> -->
        <el-table-column prop="Level" label="水质级别"> </el-table-column>
        <el-table-column prop="TargetLevel" label="目标水质"> </el-table-column>
        <el-table-column label="是否超标">
          <template slot-scope="scope"
            ><span
              :style="{ color: scope.row.IsOvers == 0 ? '#13ce66' : '#ff4949' }"
            >
              {{ scope.row.IsOvers == 0 ? "达标" : "超标" }}
            </span></template
          >
        </el-table-column>
        <!-- <el-table-column prop="waterQuality" label="水质评价" >
                </el-table-column>
                <el-table-column prop="evaluationTrend" label="水质变化趋势" >
                </el-table-column> -->
        <el-table-column
          prop="overstandarddescribe"
          label="超标描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="数据来源"
          prop="dataSource"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          min-width="100"
          v-for="(item, index) in businessList"
          :key="index"
          :label="getDataLabel(item)"
          show-overflow-tooltip
        >
          <template slot-scope="scope">{{
            scope.row[item.itemCode + "_Val"]
          }}</template>
          <!-- {{
                        scope.row[item.itemCode + '_unit'] }} -->
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import {
  bussinessItemData,
  manualMonitorData,
  manualMonitordataLastTime,
} from "@/api/dataResources/waterJcData/sgMonitor";
export default {
  name: "rightTable",
  props: {
    checkedTreeNodes: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dataRange: "",
      originDate: "",
      daysdate: "",
      beginTime: "",
      endTime: "",
      isOver: false,
      bussinessItemList: [],
      bussinessData: "",
      tableData: [],
      businessList: [],
      tabData: "river",
      total: 0,
      pageNum: 1,
      pageSize: 10,
    };
  },
  created() {
    this.query();
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.handleQuery();
    },
    // 根据传入的日期（格式：YYYY-MM）往前推半年获取对应的年月
    getDateMinusHalfYear(originDate) {
      // 检查是否是字符串格式的日期
      if (typeof originDate === "string") {
        const [year, month] = originDate.split("-").map(Number);
        // 创建日期对象
        const date = new Date(year, month - 1);
        // 减去6个月
        date.setMonth(date.getMonth() - 6);
        // 格式化返回新日期
        const newYear = date.getFullYear();
        const newMonth = String(date.getMonth() + 1).padStart(2, "0");
        return `${newYear}-${newMonth}`;
      }
      return originDate; // 如果不是字符串格式，原样返回
    },
    // 获取指定日期所在月份的最后一天
    getMonthLastDay(date) {
      let d = new Date(date);
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      // 下个月第一天的前一天就是当月最后一天
      let lastDay = new Date(year, month, 0);
      return this.parseTime(lastDay, "{yyyy}-{mm}-{dd}");
    },

    async manualMonitordataLastTime() {
      try {
        const res = await manualMonitordataLastTime();
        if (res.code == 200) {
          this.originDate = res.data.dataTime || new Date();
          this.daysdate = this.originDate;
          const prevDate = this.getDateMinusHalfYear(this.originDate);
          this.dataRange = [prevDate, this.originDate];
        }
      } catch (error) {
        console.error("Error fetching last time data:", error);
      }
    },
    selectedItems() {
      return this.bussinessData.map((itemCode) => {
        const item = this.bussinessItemList.find(
          (option) => option.itemCode === itemCode
        );
        return item;
      });
    },
    selectChange() {
      this.handleQuery();
    },
    getParams() {
      this.businessList = this.selectedItems();
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        beginTime: this.parseTime(this.daysdate, "{yyyy}-{mm}"),
        endTime: this.parseTime(this.daysdate, "{yyyy}-{mm}"),
        isOver: this.isOver ? 1 : 2,
        bussinessCategoryCode: "CBN",
      };
      if (this.tabData === "region") {
        params.beginTime = this.parseTime(
          this.dataRange[0],
          "{yyyy}-{mm}-{dd}"
        );
        params.endTime = this.getMonthLastDay(this.dataRange[1]);
      }
      params.segmentId = this.checkedTreeNodes
        .filter((item) => item.pId !== "0")
        .map((item) => item.id)
        .join(",");
      params.itemCode = this.bussinessData.join(",");
      return params;
    },
    getDataLabel(data) {
      let item = this.bussinessItemList.find((item) => item.itemCode === data.itemCode);
      if (item) {
        return item.itemNameUnit;
      }
      return data.itemNameUnit;
    },
    resetQuery() {
      // this.bussinessData = ""
      this.daysdate = this.originDate;
      this.handleQuery();
    },
    handleQuery() {
      let params = this.getParams();
      console.log("params", params);
      manualMonitorData(params).then((res) => {
        if (res.code == 200) {
          if (res.rows) {
            this.tableData = res.rows;
            this.total = res.total;
          } else {
            this.tableData = res.data;
            this.total = res.data.length;
          }
        }
      });
    },
    changeSwitch(val) {
      this.isOver = val;
    },
    changeDate(val) {
      this.beginTime = this.parseTime(val[0], "{yyyy}-{mm}-{dd}");
      this.endTime = this.parseTime(val[1], "{yyyy}-{mm}-{dd}");
    },
    async query() {
      await this.manualMonitordataLastTime();
      await this.getBussinessItemData();
      await this.handleQuery();
    },
    async getBussinessItemData() {
      try {
        const res = await bussinessItemData({ bussinessCategoryCode: "CBN" });
        if (res.code == 200) {
          this.bussinessItemList = res.data;
          this.bussinessData = res.data.map((item) => item.itemCode);
          this.businessList = this.selectedItems();
        }
      } catch (error) {
        console.error("Error fetching business items:", error);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.r-header {
  display: flex;
  justify-content: left;
  align-items: center;
}

.header-item {
  margin-right: 10px;
}

.header-btns {
  display: flex;
  margin-top: 10px;
}

.content {
  margin-top: 10px;
}
</style>
